<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPigSearch;
use common\components\Upload;
use common\models\business\BusinessContractCategory;
use common\models\business\BusinessPig;
use Yii;
use common\models\business\BusinessPigFile;
use backend\modules\business\models\BusinessPigFileSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * PigFileController implements the CRUD actions for BusinessPigFile model.
 */
class PigFileController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessPigFile models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessPigFileSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessPigFile model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessPigFile model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessPigFile();

        if ($model->load(Yii::$app->request->post())){
            if(false !== $photo = Upload::upload($model,'matherphoto')){
                $model->setAttribute('matherphoto',$photo);
            }
            if(false !== $photo = Upload::upload($model,'fatherphoto')){
                $model->setAttribute('fatherphoto',$photo);
            }
            if($model->save()){


                $postdata = Yii::$app->request->post();
                if(!empty($postdata['BusinessPigFile']['pigs'])) {
                    foreach ($postdata['BusinessPigFile']['pigs'] as $key => $row) {
                        Yii::$app->db->createCommand()->update(BusinessPig::tableName(), ['fileid' => $model->id], 'id=:id', [':id' => $row])
                            ->execute();
                    }
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }

            return $this->timeAlert($this->checkError($model));

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessPigFile model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())){
            if(false !== $photo = Upload::upload($model,'matherphoto')){
                $model->setAttribute('matherphoto',$photo);
            }
            if(false !== $photo = Upload::upload($model,'fatherphoto')){
                $model->setAttribute('fatherphoto',$photo);
            }
            if($model->save()){
                $postdata = Yii::$app->request->post();
                $pids = (new Query())->select('id,no')->from(BusinessPig::tableName())
                    ->where('fileid=:id',[':id'=>$model->id])
                    ->all();
                if(!empty($pids)){
                    $pids = ArrayHelper::getColumn($pids,'id');
                }else{
                    $pids = [];
                }
                if(!empty($postdata['BusinessPigFile']['pigs'])){
                    $diff = array_diff($pids,$postdata['BusinessPigFile']['pigs']);
                    foreach ($postdata['BusinessPigFile']['pigs'] as $key => $row){
                        Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['fileid'=>$model->id],'id=:id',[':id'=>$row])
                            ->execute();
                    }
                }else{
                    $diff = $pids;
                }

                //去掉删除的
                foreach ($diff as $key => $row){
                    Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['fileid'=>0],'id=:id',[':id'=>$row])
                        ->execute();
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->timeAlert($this->checkError($model));
        }
        else {
            $pids = (new Query())->select('id,no')->from(BusinessPig::tableName())
                ->where('fileid=:id',[':id'=>$model->id])
                ->all();
            $ids = [];
            foreach ($pids as $key => $row){
                $ids[$row['id']] = '['.$row['id'].']'.$row['no'].']';
            }

            return $this->render('update', [
                'model' => $model,
                'ids' => $ids
            ]);
        }
    }

    /**
     * Deletes an existing BusinessPigFile model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }


    /**
     * 添加仔猪
     */
    public function actionAddpig()
    {
        if(Yii::$app->request->isPost){
            $postdata = Yii::$app->request->post();
            $fileinfo = BusinessPigFile::find()->where(['id'=>$postdata['id']])->asArray()->one();
            foreach ($postdata['ids'] as $key => $row){
                $result = Yii::$app->db->createCommand('update '.BusinessPig::tableName().' set fileid=:fileid,batch=:batch where id=:id')
                    ->bindValues([':fileid'=>$fileinfo['id'],':batch'=>$fileinfo['no'],':id'=>$row])
                    ->execute();
            }
            Yii::$app->response->format = Response::FORMAT_JSON;
            return $result?['msg'=>'更新成功','status'=>0]:['msg'=>'更新失败','status'=>1];
        }


        $searchModel = new BusinessPigSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('/pig/index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'id' => Yii::$app->request->get('id')
        ]);

    }

    /**
     * Finds the BusinessPigFile model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessPigFile the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessPigFile::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
